from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn

# 创建app对象
app = FastAPI()


# 创建一个模型Book类
class Book(BaseModel):
    id: int
    title: str
    author: str
    price: float


# 测试数据
books = [
    {"id": 1, "title": "看漫画学Python", "author": "关东升", "price": 29.99},
    {"id": 2, "title": "杀死一只知更鸟", "author": "Harper Lee", "price": 19.99},
    {"id": 3, "title": "Python从小白到大牛", "author": "关东升", "price": 49.99},
    {"id": 4, "title": "漫画Java", "author": "关东升", "price": 39.99},
]


# 定义路由行
@app.get("/books/{book_id}", response_model=Book)
async def read_book(book_id: int):
    for book in books:
        if book["id"] == book_id:
            return Book(**book)

    return {"error": "图书额没有找到"}


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
